package com.manbu.springcloud.ribbonrule;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
public class MyRibbonRule extends AbstractLoadBalancerRule {
    public MyRibbonRule() {
    }

    // 改造标准 每个机器访问五次 换下一个服务
    // total 指针 默认等于0  如果等于5 指向下一个服务节点
    //index 默认等于0 如果total=5 index+1 如果index>3 index =0 total=0

    private int total=0;// 被调用的次数
    private int currentIndex=0;//当前提供的服务
    //@SuppressWarnings({"RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE"})
    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        } else {
            Server server = null;

            while(server == null) {
                if (Thread.interrupted()) {
                    return null;
                }
                // 获取还活着的服务
                List<Server> upList = lb.getReachableServers();
                // 获得全部服务
                List<Server> allList = lb.getAllServers();
                int serverCount = allList.size();
                if (serverCount == 0) {
                    return null;
                }
        /*        //生成区间随机数
                int index = this.chooseRandomInt(serverCount);
                //从活着的服务 获取其中的某一个
                server = (Server)upList.get(index);*/
                //=====================
                    if (total<5){
                        server=upList.get(currentIndex);
                        total++;
                    }else {
                        total=0;
                        currentIndex++;
                        if (currentIndex>upList.size()){
                            currentIndex=0;
                            upList = lb.getReachableServers();
                        }
                        upList.get(currentIndex);
                    }
                //=====================

                if (server == null) {
                    Thread.yield();
                } else {
                    if (server.isAlive()) {
                        return server;
                    }

                    server = null;
                    Thread.yield();
                }
            }

            return server;
        }
    }

    protected int chooseRandomInt(int serverCount) {
        return ThreadLocalRandom.current().nextInt(serverCount);
    }

    @Override
    public Server choose(Object key) {
        return this.choose(this.getLoadBalancer(), key);
    }

    @Override
    public void initWithNiwsConfig(IClientConfig clientConfig) {
        //TODO Auto-generated method stub
    }
}
